package cn.hh.wechatkit.api.token;

import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidParam;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hh.wechatkit.pojo.token.WxApp_OpenIdSession;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import okhttp3.Response;

import java.io.IOException;

import static cn.hh.wechatkit.helper.WxConst.JsCode2Session_GET_URL;

/**
 * Created this one by HMH on 2018/8/21.
 */
@Slf4j
public class WxAPI_Access_GetOpenId_Api {

    //get请求，获取access_token
    public static WxApp_OpenIdSession getOpenIdSession(String appId, String appsecret, String js_code) {
        String url = JsCode2Session_GET_URL.replace("APPID", appId).replace("SECRET", appsecret).replace("JSCODE", js_code);
        Response response = null;
        try {
            response = httpUtil.get(url);
            if (response != null) {
                try {
                    Headers headers = response.headers();
                    String body = response.body().string();
                    //解析字符串
                    WxApp_OpenIdSession wxAppOpenIdSession = JSON.parseObject(body, WxApp_OpenIdSession.class);
                    if (wxAppOpenIdSession.getErrcode() != null) {
                        throw new Wx_Exception_InvalidParam(wxAppOpenIdSession.getErrmsg());
                    }
                    return wxAppOpenIdSession;
                } catch (IOException e) {
                    log.error("处理返回的AccessToken发生错误\n", e);
                    throw new Wx_Exception_InvalidJsonParse("处理返回的AccessToken发生错误\n", e);
                }
            }
        } catch (IOException e) {
            log.error("accessToken接口请求失败");
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
